package tripx.plan;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import tripx.sql.SqlAction;

public class PlanServiceConfig {

	private static PlanServiceConfig config;

	private Document configDoc;

	private PlanServiceConfig() {
		try {
			configDoc = DocumentBuilderFactory.newInstance()
					.newDocumentBuilder().parse(new File("./config/plan.xml"));
		} catch (SAXException | IOException | ParserConfigurationException e) {
			e.printStackTrace();
		}
	}

	public static PlanServiceConfig getInstance() {
		if (config == null) {
			config = new PlanServiceConfig();
		}
		return config;
	}

	public ArrayList<SqlAction> getQueryActionList() {
		ArrayList<SqlAction> queryActionList = new ArrayList<SqlAction>();
		Element root = configDoc.getDocumentElement();
		NodeList nodeList = root.getElementsByTagName("action");
		for (int i = 0; i < nodeList.getLength(); i++) {
			Element ele = (Element) nodeList.item(i);
			queryActionList.add(new SqlAction(ele.getAttribute("key"), ele
					.getAttribute("sql"), Integer.parseInt(ele
					.getAttribute("paramCount"))));
		}
		return queryActionList;
	}

	public String getPlanTableName() {
		Element root = configDoc.getDocumentElement();
		NodeList nodeList = root.getElementsByTagName("table");
		for (int i = 0; i < nodeList.getLength(); i++) {
			Element ele = (Element) nodeList.item(i);
			if (ele.getAttribute("id").equals("plan")) {
				return ele.getAttribute("name");
			}
		}
		return "";
	}

	public String getPlanCityTableName() {
		Element root = configDoc.getDocumentElement();
		NodeList nodeList = root.getElementsByTagName("table");
		for (int i = 0; i < nodeList.getLength(); i++) {
			Element ele = (Element) nodeList.item(i);
			if (ele.getAttribute("id").equals("planCity")) {
				return ele.getAttribute("name");
			}
		}
		return "";
	}
}
